
package com.heiyu.controller.config;

import com.alibaba.fastjson.JSON;
import com.heiyu.entity.AdminInfo;
import com.heiyu.entity.AdminUserInfo;
import com.heiyu.entity.UserInfo;
import com.heiyu.utils.CacheKey;
import com.heiyu.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CorsFilter implements Filter {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void init(FilterConfig filterConfig)  {

    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request  = (HttpServletRequest) req;
       /* if(!(request.getServletPath().equals("/login"))){
            String token = request.getHeader("Authorization");
            if(StringUtils.isEmpty(token)){
                response(response,"{\"code\":\"4001\",\"msg\":\"登录失效请重新登录\",\"data\":\"\"}");
                return;
            }
            String userStr = redisUtils.get(CacheKey.ADMIN_TOKEN+token);
            if(StringUtils.isEmpty(userStr)){
                response(response,"{\"code\":\"4001\",\"msg\":\"登录失效请重新登录\",\"data\":\"\"}");
                return;
            }
            AdminUserInfo userInfo = JSON.parseObject(redisUtils.get(CacheKey.ADMIN_TOKEN+token),AdminUserInfo.class);
            if(userInfo == null){
                response(response,"{\"code\":\"4001\",\"msg\":\"登录失效请重新登录\",\"data\":\"\"}");
                return;
            }
        }*/
        try{
            chain.doFilter(req, res);
        }catch (Exception e){
            e.printStackTrace();
            response(response,"{\"code\":\"3001\",\"msg\":\"系统繁忙\",\"data\":\"\"}");
        }

    }

    private void response(HttpServletResponse response,String msg) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(msg);
        out.close();
    }

    @Override
    public void destroy() {

    }
}

